<?php

namespace app\admin\controller\manufacture;

use app\common\controller\Backend;
use think\Db;
use Exception;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 成本管理
 *
 * @icon fa fa-dollar-sign
 * @remark 管理生产成本核算
 */
class Cost extends Backend
{
    /**
     * Cost模型对象
     * @var \app\admin\model\manufacture\Cost
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\manufacture\Cost;
        $this->view->assign("typeList", $this->model->getTypeList());
        $this->view->assign("statusList", $this->model->getStatusList());
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->with(['plan.order', 'costType'])
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            $result = array("total" => $list->total(), "rows" => $list->items());
            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        // 获取生产计划列表
        $planList = \app\admin\model\manufacture\Plan::with(['order'])
            ->where('status', 'running')
            ->select();
        $this->view->assign('planList', $planList);
        
        // 获取成本类型列表
        $costTypeList = \app\admin\model\manufacture\CostType::where('status', 1)->select();
        $this->view->assign('costTypeList', $costTypeList);
        
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                
                // 生成成本编号
                $params['cost_no'] = $this->generateCostNo();
                $params['creator_id'] = $this->auth->id;
                
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    $result = $this->model->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            } else {
                $this->error(__('Parameter %s can not be empty', ''));
            }
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        
        // 获取生产计划列表
        $planList = \app\admin\model\manufacture\Plan::with(['order'])
            ->where('status', 'running')
            ->select();
        $this->view->assign('planList', $planList);
        
        // 获取成本类型列表
        $costTypeList = \app\admin\model\manufacture\CostType::where('status', 1)->select();
        $this->view->assign('costTypeList', $costTypeList);
        
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            } else {
                $this->error(__('Parameter %s can not be empty', ''));
            }
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        if ($ids) {
            $pk = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $list = $this->model->where($pk, 'in', $ids)->select();

            $count = 0;
            Db::startTrans();
            try {
                foreach ($list as $item) {
                    $count += $item->delete();
                }
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        } else {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }
    }

    /**
     * 成本统计
     */
    public function statistics()
    {
        // 获取成本统计数据
        $data = [
            'total_cost' => $this->model->sum('amount'),
            'today_cost' => $this->model->whereTime('createtime', 'today')->sum('amount'),
            'month_cost' => $this->model->whereTime('createtime', 'month')->sum('amount'),
            'year_cost' => $this->model->whereTime('createtime', 'year')->sum('amount'),
        ];
        
        // 按成本类型统计
        $costByType = $this->model->alias('c')
            ->join('manufacture_cost_type ct', 'c.cost_type_id = ct.id')
            ->field('ct.name, SUM(c.amount) as total_amount')
            ->group('c.cost_type_id')
            ->select();
        
        // 按月份统计
        $costByMonth = [];
        for ($i = 11; $i >= 0; $i--) {
            $month = date('Y-m', strtotime("-{$i} months"));
            $amount = $this->model->whereTime('createtime', $month)->sum('amount');
            $costByMonth[] = [
                'month' => date('m', strtotime($month)),
                'amount' => $amount ?: 0
            ];
        }
        
        $this->view->assign('data', $data);
        $this->view->assign('costByType', $costByType);
        $this->view->assign('costByMonth', json_encode($costByMonth));
        
        return $this->view->fetch();
    }

    /**
     * 成本分析
     */
    public function analysis()
    {
        $type = $this->request->get('type', 'monthly');
        
        switch ($type) {
            case 'monthly':
                $data = $this->getMonthlyAnalysis();
                break;
            case 'plan':
                $data = $this->getPlanAnalysis();
                break;
            case 'type':
                $data = $this->getTypeAnalysis();
                break;
            default:
                $data = [];
        }
        
        $this->view->assign('type', $type);
        $this->view->assign('data', $data);
        
        return $this->view->fetch();
    }

    /**
     * 获取月度分析数据
     */
    private function getMonthlyAnalysis()
    {
        $data = [];
        
        // 最近12个月的成本数据
        for ($i = 11; $i >= 0; $i--) {
            $month = date('Y-m', strtotime("-{$i} months"));
            $total = $this->model->whereTime('createtime', $month)->sum('amount');
            $count = $this->model->whereTime('createtime', $month)->count();
            
            $data['months'][] = date('m月', strtotime($month));
            $data['amounts'][] = $total ?: 0;
            $data['counts'][] = $count;
        }
        
        return $data;
    }

    /**
     * 获取计划分析数据
     */
    private function getPlanAnalysis()
    {
        $data = $this->model->alias('c')
            ->join('manufacture_plan p', 'c.plan_id = p.id')
            ->join('scanwork_order o', 'p.order_id = o.id')
            ->field('p.plan_name, o.order_no, SUM(c.amount) as total_cost, COUNT(c.id) as cost_count')
            ->group('c.plan_id')
            ->order('total_cost desc')
            ->limit(10)
            ->select();
        
        return $data;
    }

    /**
     * 获取类型分析数据
     */
    private function getTypeAnalysis()
    {
        $data = $this->model->alias('c')
            ->join('manufacture_cost_type ct', 'c.cost_type_id = ct.id')
            ->field('ct.name, SUM(c.amount) as total_amount, COUNT(c.id) as count')
            ->group('c.cost_type_id')
            ->order('total_amount desc')
            ->select();
        
        return $data;
    }

    /**
     * 生成成本编号
     */
    private function generateCostNo()
    {
        $prefix = 'COST';
        $date = date('Ymd');
        $random = strtoupper(substr(md5(uniqid()), 0, 6));
        return $prefix . $date . $random;
    }
}
